package com.thwj.framework.web.service;

import cn.hutool.core.lang.Dict;
import com.thwj.common.constant.Constants;
import com.thwj.common.enums.DeptEnum;
import com.thwj.common.enums.UserTypeEnum;
import com.thwj.common.exception.ServiceException;
import com.thwj.common.exception.user.CaptchaException;
import com.thwj.common.exception.user.CaptchaExpireException;
import com.thwj.common.exception.user.UserPasswordNotMatchException;
import com.thwj.common.utils.DateUtils;
import com.thwj.common.utils.MessageUtils;
import com.thwj.common.utils.ServletUtils;
import com.thwj.common.utils.StringUtils;
import com.thwj.common.utils.ip.IpUtils;
import com.thwj.framework.manager.AsyncManager;
import com.thwj.framework.manager.factory.AsyncFactory;
import com.thwj.framework.redis.RedisCache;
import com.thwj.framework.security.LoginUser;
import com.thwj.project.system.domain.SysUser;
import com.thwj.project.system.service.ISysConfigService;
import com.thwj.project.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 登录校验方法
 *
 * @author 可乐
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysPermissionService permissionService;


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
        if (captchaOnOff) {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }


    /**
     * <b>方法名：</b>陪玩官微信登入<br>
     * <b>说明：</b> <br>
     *
     * @param phoneNumber
     * @param openId
     * @return java.lang.String
     * <b>修改履历：</b>
     * @author 可乐
     */
    public Dict servantLoginWx(String phoneNumber, String openId) {
        SysUser user = userService.selectUserByOpenId(openId);
        if (StringUtils.isNull(user)) {
            user = new SysUser();
            user.setUserName(openId);
            user.setNickName(openId);
            user.setStatus("0");
            user.setUserType(UserTypeEnum.SERVANT.getCode());
            user.setDeptId(DeptEnum.DEPT_PLAYER.getCode());
            if (StringUtils.isEmpty(phoneNumber)) {
                user.setPhonenumber(phoneNumber);
            }
            user.setOpenId(openId);
            userService.insertUser(user);
        } else {
            if (Integer.valueOf(user.getStatus()) == 1) {
                Dict dict = new Dict();
                dict.put("token", "0");
                return dict;
            }
        }
        if (StringUtils.isEmpty(user.getPhonenumber()) && !StringUtils.isEmpty(phoneNumber)) {
            SysUser update = new SysUser();
            update.setPhonenumber(phoneNumber);
            update.setUserId(user.getUserId());
            userService.updateUserProfile(update);
        }

        UserDetails userDetails = new LoginUser(user, permissionService.getMenuPermission(user));
        Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null,
                AuthorityUtils.createAuthorityList("ROLE_USER"));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成token
        Dict dict = new Dict();
        dict.put("token", tokenService.createToken(loginUser));


        return dict;
    }


    /**
     * <b>方法名：</b>玩家公众号登录<br>
     * <b>说明：</b> <br>
     *
     * @param openId
     * @return java.lang.String
     * <b>修改履历：</b>
     * @author 可乐
     */
    /*public Dict playerLoginWx(String accessToken, String openId) {
        SysUser user = userService.selectUserByOpenId(openId);
        if (StringUtils.isNull(user)) {
            String userInfoResult = WxUtils.getGzhUserInfo(accessToken, openId);
            if (!JSONUtil.isJsonObj(userInfoResult)) {
                return null;
            }
            JSONObject jsonObject = new JSONObject(userInfoResult);
            user = new SysUser();
            user.setUserName(openId);
            user.setNickName(String.valueOf(jsonObject.get("nickname")));
            user.setAvatar(String.valueOf(jsonObject.get("headimgurl")));
            if (String.valueOf(jsonObject.get("sex")) == "0") {
                user.setSex("2");
            } else if (String.valueOf(jsonObject.get("sex")) == "1") {
                user.setSex("0");
            } else if (String.valueOf(jsonObject.get("sex")) == "2") {
                user.setSex("1");
            }
            user.setUserType(UserTypeEnum.PLAYER.getCode());
            user.setDeptId(DeptEnum.DEPT_PLAYER.getCode());
            user.setPhonenumber("");
            user.setOpenId(openId);
            if (userService.insertUser(user) <= 0) {
                return null;
            }

        } else {
            if (Integer.valueOf(user.getStatus()) == 1) {
                Dict dict = new Dict();
                dict.put("token", "0");
                return dict;
            }
        }

        UserDetails userDetails = new LoginUser(user, permissionService.getMenuPermission(user));
        Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null,
                AuthorityUtils.createAuthorityList("ROLE_USER"));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        // 生成token
        Dict dict = new Dict();
        dict.put("token", tokenService.createToken(loginUser));

        return dict;

    }*/
}
